//
//  LNComposeViewController.swift
//  727-黑马08微博-测试
//
//  Created by apple on 15/8/9.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

 /// 微博文字最大长度
 private let kStatusTextMaxLength = 10

class LNComposeViewController: UIViewController, UITextViewDelegate {
    
//    键盘输入视图 -默认键盘高度216
    private lazy var emoticonVC: EmoticonViewController = EmoticonViewController {[weak self] (emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }

     func close() {
//        关闭键盘
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
/// 发布微博，两次内容不能重复
    func sendStatus() {
//        1.长度检测
        let text = textView.emoticonText
        if text.characters.count > kStatusTextMaxLength {
            SVProgressHUD.showInfoWithStatus("输入的文本太长", maskType: SVProgressHUDMaskType.Gradient)
            return
        }
        
//        发布微博
        LNNetworkTools.sharedTools.sendStatus(textView.emoticonText) { (result, error) -> () in
            print(result)
            
            print(error)
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力", maskType: SVProgressHUDMaskType.Gradient)
                return
            }
//            保证统一出口
            self.close()
        }
    }
    
    
    
    func inputEmoticon() {
        print("选择表情")
//        0.注销键盘通知
//        removeKeyboardOberserver()
//       1. 注销键盘
        textView.resignFirstResponder()
//       2. 设置输入键盘
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
//       3. 重新注册通知
//        addKeyboardOberserver()
//        4. 激活键盘
        textView.becomeFirstResponder()
    }
    
//    MARK: - UITextViewDelegate
//    如果输入的是`emoji`会跟正常文本一样，但是如果输入的是图片符号，不会调用代理方法
    func textViewDidChange(textView: UITextView) {
//        1.设置占位标签 & 按钮
//        hasText 可以检查text & attributeText
        placeholderLabel.hidden  = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
//        2.计算用户输入完整内容长度，并且提示用户
        let text = textView.emoticonText
        let len =  kStatusTextMaxLength - text.characters.count
        lengthTipLabel.text = "\(len)"
        lengthTipLabel.textColor  = len < 0 ? UIColor.redColor() :  UIColor.lightGrayColor()
    }
    
    
    
    
//    MARK: -键盘监听方法
    override func viewDidLoad() {
        super.viewDidLoad()
        addKeyboardOberserver()
        
    }
    deinit {
        removeKeyboardOberserver()
    }
/// 添加键盘通知
    private func addKeyboardOberserver() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
/// 删除键盘通知
    private func removeKeyboardOberserver() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    } 
/// toolbar底部约束
    private var toolbarBottomCons: NSLayoutConstraint?
/// 键盘变化监听方法，是由通知中心监听到之后，由运行循环来调度执行，不能设置成private的
    func keyboardChanged(n: NSNotification) {
        print(n)
        let curve = n.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
//        获取目标frame
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
//        动画时长
        let duration  = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
//        设置约束
        toolbarBottomCons?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
//        动画
        UIView.animateWithDuration(duration) {
//            设置动画的时间选项
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
//        激活键盘
        textView.becomeFirstResponder()
    }
    
    
//    MARK: - 搭建界面
    override func loadView() {
         view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        prepareNav()
        prepareToolbar()
        prepareTextView()
    }
/// 准备文本框
    private func prepareTextView() {
        view.addSubview(textView)
        textView.backgroundColor =  UIColor.whiteColor()
//        自动布局
        textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil)
        
//        添加占位标签
        placeholderLabel.text = "分享新鲜事..."
        placeholderLabel.sizeToFit()
        textView.addSubview(placeholderLabel)
        placeholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
        
//        添加长度提示标签 - 一定要添加到 `View`上
        view.addSubview(lengthTipLabel)
        lengthTipLabel.text = String(kStatusTextMaxLength)
        lengthTipLabel.sizeToFit()
        lengthTipLabel.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -8, y: -8))
        
    
       
    }
    
    
//    准备Toolbar
    private func prepareToolbar() {
//        1.创建toolbar
        
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        view.addSubview(toolbar)
        // 设置布局
        let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        // 记录底部约束
        toolbarBottomCons = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
//        定义一个数组
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"]))
//            追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        items.removeLast()
        
        toolbar.items = items
    }
    
 /// 文本视图
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
//        设置代理
        tv.delegate = self 
//        允许垂直拖拽
        tv.alwaysBounceVertical = true
//        拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return tv
    }()
 /// 占位标签
    private lazy var placeholderLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
 /// 长度提示标签
    private lazy var lengthTipLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 12)
    
    
/// 工具栏
    private lazy var toolbar = UIToolbar()
    
    
/// 准备导航栏
    private func prepareNav() {
    
//        1.左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
//        2.右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
//        3.标题栏
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        let titleLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
        titleLabel.text = "发微博"
        titleLabel.sizeToFit()
        titleView.addSubview(titleLabel)
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        
        let nameLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 13)
        nameLabel.text = LNUserAccount.sharedAccount?.name ?? ""
        nameLabel.sizeToFit()
        titleView.addSubview(nameLabel)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        navigationItem.titleView = titleView
        
        
    }
}
